import {
  useAddArticle,
  useGetOneArticle,
  useUpdateArticle,
} from '@/services/article';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { PageContainer, ProCard } from '@ant-design/pro-components';
import { history, useIntl, useModel } from '@umijs/max';
import {
  Button,
  Form,
  Input,
  message,
  Radio,
  Space,
  Switch,
  Tag,
  Upload,
  UploadProps,
} from 'antd';
import { useEffect, useMemo, useState } from 'react';
import 'react-quill/dist/quill.snow.css';
import RichTextEditor from './components/RichTextEditor';
import { DashProCard } from './components/style';
import TagButton from './components/TagButton';
import dayjs from 'dayjs';
import { UploadChangeParam, UploadFile } from 'antd/es/upload';
import ImgCrop from 'antd-img-crop';
import QUERY_KEYS from '@/services/constant';
import { clearDraft, getDraft, setDraft } from '@/utils/draft';
import TextArea from 'antd/es/input/TextArea';
import { useSearchParams } from '@umijs/max';
import { ARTICLES_SOURCE, NEWS_TYPE } from '@/services/constant/articles';
import { beforeUpload } from '@/utils/upload';

const ArticleTypeList = ['common', 'question'];

const tagList = NEWS_TYPE;
const tagList2 = ['技术', '记录', '科普', '资源'];

const isSelectNewsTags = (tags: string) => {
  return tags.length > 0 && tags.split('/').some((x) => tagList.includes(x));
};

let draft: API.IArticles | null = getDraft();

const Write: React.FC = () => {
  const [searchParams] = useSearchParams();
  const intl = useIntl();
  const { initialState } = useModel('@@initialState');
  const [content, setContent] = useState<string>('');
  const [title, setTitle] = useState<string>('');
  const [introduction, setIntroduction] = useState<string>('');
  const [isChange, setIsChange] = useState<boolean>(false);
  const [isQuestion, setIsQuestion] = useState<number | string>(
    parseInt(searchParams.get('isQ') ?? '0'),
  );
  const [isDone, setIsDone] = useState<number>();
  const [isNews, setIsNews] = useState<number>();
  const { mutateAsync: addArticle } = useAddArticle(initialState?.id ?? -1);
  const getOneAticleQuery = useGetOneArticle(
    parseInt(searchParams.get('id') ?? '-1'),
    false,
  );
  const { mutateAsync: updateArticle } = useUpdateArticle();

  // 标签
  const [isShowTags, setIsShowTags] = useState<boolean>(false);
  const [tags, setTags] = useState<string[]>([]);
  const cancelTag = (tag: string) => {
    setTags(tags.filter((t) => t !== tag));
  };
  const [selfTag, setSelfTag] = useState<string>('');
  const addSelfTag = () => {
    setTags((pre) => [...pre, selfTag]);
    setSelfTag('');
  };

  // 文章来源
  const [articleSource, setArticleSource] = useState<number>(0);

  // 图片
  const [avatar, setAvatar] = useState<string>('');
  const [loading, setLoading] = useState<boolean>(false);
  const handleChange: UploadProps['onChange'] = (
    info: UploadChangeParam<UploadFile>,
  ) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      if (info.file.response.code === 200) {
        setLoading(false);
        setAvatar(info.file.response.data.url);
      }
    }
  };

  const uploadButton = useMemo(
    () => <div>{loading ? <LoadingOutlined /> : <PlusOutlined />}</div>,
    [loading],
  );

  useEffect(() => {
    if (searchParams.get('id')) {
      if (draft?.id?.toString() !== searchParams.get('id')) {
        draft = setDraft({
          ...draft,
          id: parseInt(searchParams.get('id') as string),
        });

        getOneAticleQuery.refetch();
      }
    } else if (draft?.id) {
      draft = clearDraft();
    }
  }, []);

  const setForm = (data: API.IArticles) => {
    setTitle(data.title);
    setIntroduction(data.introduction);
    setContent(data.content ?? '');
    setAvatar(data.avatar ?? '');
    setIsQuestion((data.isQuestion ?? 0) as number);
    setIsDone(data.isDone ?? 0);
    setIsNews(data.isNews ?? 0);
    setTags(
      data.tags?.length && data.tags?.length > 0
        ? data.tags?.split('/') ?? []
        : [],
    );
    setArticleSource(data.articleSource);
  };

  useEffect(() => {
    if (getOneAticleQuery.isSuccess) {
      let data = getOneAticleQuery.data?.data;
      if (data && data.id) setForm(data);
    } else if (draft) {
      setForm(draft);
    }
  }, [getOneAticleQuery.isSuccess]);

  useEffect(() => {
    if (getOneAticleQuery.isSuccess) {
      draft = setDraft({
        ...draft,
        title,
        introduction,
        isQuestion,
        isDone,
        isNews,
        content,
        avatar,
        articleSource,
        tags: tags.join('/'),
      });
    } else if (isChange) {
      draft = setDraft({
        ...draft,
        title,
        introduction,
        isQuestion,
        isDone,
        isNews,
        content,
        avatar,
        articleSource,
        tags: tags.join('/'),
      });
    }
    setIsChange(true);
  }, [
    title,
    introduction,
    content,
    avatar,
    articleSource,
    tags,
    isQuestion,
    isDone,
    isNews,
  ]);

  // 发布
  const submit = () => {
    if (title.length === 0) {
      message.error('请输入标题');
      return;
    } else if (introduction.length === 0) {
      message.error('请输入简介');
      return;
    } else if (content.length === 0) {
      message.error('请输入内容');
      return;
    } else if (avatar.length === 0) {
      message.error('请输入封面');
      return;
    } else if (tags.length === 0) {
      message.error('请输入标签');
      return;
    } else if (isNews === 1 && !isSelectNewsTags(tags.join('/'))) {
      message.error('请选择咨询标签');
      return;
    }
    if (draft?.id) updateArticle({ ...draft, accountId: initialState?.id });
    else
      addArticle({
        title,
        introduction,
        isQuestion,
        isDone,
        isNews,
        content,
        avatar,
        articleSource,
        tags: tags.join('/'),
        time: dayjs().format('YYYY-MM-DD hh:mm:ss'),
      });
  };
  // 重置
  const reset = () => {
    clearDraft();
    window.location.reload();
  };
  // 取消
  const cancel = () => {
    clearDraft();
    history.back();
  };
  return (
    <PageContainer
      header={{
        title: '',
      }}
    >
      <Space direction="vertical">
        <ProCard>
          <Form>
            <Form.Item label="标题">
              <TextArea
                value={title}
                onChange={(e) => setTitle(e.target.value)}
                rows={2}
                maxLength={100}
              ></TextArea>
            </Form.Item>
            <Form.Item label="简介">
              <TextArea
                value={introduction}
                onChange={(e) => setIntroduction(e.target.value)}
                rows={4}
                maxLength={100}
              />
            </Form.Item>
            <Form.Item name="content" label="内容">
              <RichTextEditor
                text={content}
                setText={setContent}
              ></RichTextEditor>
            </Form.Item>
          </Form>
        </ProCard>

        <ProCard>
          <Form>
            <Form.Item label="封面" rules={[{ required: true }]}>
              <ImgCrop aspect={1.5}>
                <Upload
                  name="file"
                  listType="picture-card"
                  className="avatar-uploader"
                  maxCount={1}
                  showUploadList={false}
                  action={QUERY_KEYS.UPLOAD_IMAGE_URL}
                  beforeUpload={beforeUpload}
                  onChange={handleChange}
                >
                  {avatar ? (
                    <img src={avatar} alt="avatar" style={{ width: '100%' }} />
                  ) : (
                    uploadButton
                  )}
                </Upload>
              </ImgCrop>
            </Form.Item>
            <Form.Item label="标签" rules={[{ required: true }]}>
              <Space>
                {tags.length > 0 &&
                  tags.map((tag, index) => (
                    <Tag key={index} closable onClose={() => cancelTag(tag)}>
                      {tag}
                    </Tag>
                  ))}
              </Space>
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={() => setIsShowTags(!isShowTags)}
              ></Button>
            </Form.Item>
            {isShowTags ? (
              <Form.Item>
                <Space style={{ marginBottom: '20px' }}>
                  <Input.Group compact>
                    <Input
                      style={{ width: 'calc(100% - 50px)' }}
                      placeholder="自定义标签"
                      value={selfTag}
                      onChange={(e) => setSelfTag(e.target.value)}
                    />
                    <Button
                      type="primary"
                      disabled={selfTag.length === 0}
                      icon={<PlusOutlined />}
                      onClick={addSelfTag}
                    ></Button>
                  </Input.Group>
                </Space>
                <DashProCard>
                  <Space wrap>
                    {isNews === 1
                      ? tagList.map((tag) => (
                          <TagButton
                            key={tag}
                            select={() => setTags((pre) => [...pre, tag])}
                            cancel={() => cancelTag(tag)}
                          >
                            {tag}
                          </TagButton>
                        ))
                      : ''}
                    {tagList2.map((tag) => (
                      <TagButton
                        key={tag}
                        select={() => setTags((pre) => [...pre, tag])}
                        cancel={() => cancelTag(tag)}
                      >
                        {tag}
                      </TagButton>
                    ))}
                  </Space>
                </DashProCard>
              </Form.Item>
            ) : (
              ''
            )}

            <Form.Item label="文章来源" rules={[{ required: true }]}>
              <Radio.Group
                value={ARTICLES_SOURCE[articleSource]}
                onChange={(e) =>
                  setArticleSource(ARTICLES_SOURCE.indexOf(e.target.value))
                }
              >
                {ARTICLES_SOURCE.map((text, index) => (
                  <Radio value={text} key={index}>
                    {intl.formatMessage({
                      id: `article.articleSource.${text}`,
                    })}
                  </Radio>
                ))}
              </Radio.Group>
            </Form.Item>
            {articleSource === 1 ? (
              <Form.Item label="是否资讯">
                <Switch
                  defaultChecked={isNews === 1}
                  checkedChildren="咨讯"
                  unCheckedChildren="普通"
                  onChange={(e) => setIsNews(e === true ? 1 : 0)}
                />
              </Form.Item>
            ) : (
              ''
            )}
            <Form.Item label="文章类型" rules={[{ required: true }]}>
              <Radio.Group
                value={parseInt(isQuestion as string)}
                onChange={(e) => setIsQuestion(e.target.value)}
              >
                {ArticleTypeList.map((text, index) => (
                  <Radio value={index} key={index}>
                    {intl.formatMessage({
                      id: `article.articleType.${text}`,
                    })}
                  </Radio>
                ))}
              </Radio.Group>
            </Form.Item>
            {isQuestion === 1 ? (
              <Form.Item label="是否解决">
                <Switch
                  defaultChecked={isDone === 1}
                  checkedChildren="已解决"
                  unCheckedChildren="未解决"
                  onChange={(e) => setIsDone(e === true ? 1 : 0)}
                />
              </Form.Item>
            ) : (
              ''
            )}

            <Space align="center">
              <Button type="primary" onClick={submit}>
                发布
              </Button>
              <Button type="primary" onClick={cancel}>
                取消
              </Button>
              <Button type="primary" onClick={reset}>
                重置
              </Button>
            </Space>
          </Form>
        </ProCard>
      </Space>
    </PageContainer>
  );
};

export default Write;
